<?php

namespace control;
/*
*待检验钢瓶
*/

class inspectSteelCylinderClass extends adIndexClass
{
    private const page = 'inspectSteelCylinder'; # 权限
    private const table = 'steel_cylinder'; # 数据表
    private const title = '待检验钢瓶';

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'barcode' => [
                'name'  => '内部编码',
                'width' => 200,
                'sort' => 1,
            ],
            'code' => [
                'name'  => '出厂码',
                'width' => 200,
                'sort' => 1,
            ],
            'model'  => [
                'name'  => '规格型号',
                'width' => 200,
            ],
            'nextTime'         => [
                'name'  => '下次检验日期',
                'width' => 200,
            ],
            'wenTime'         => [
                'name'  => '最近检验日期',
                'width' => 200,
            ],
            'dtTime'         => [
                'name'  => '制造日期',
                'width' => 200,
            ],
        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '安检码'   => text(array("name" => "barcode")),
                    '出厂码'   => text(array("name" => "code")),
                    '规格型号'  => text(array("name" => "model")),
                ],
                [
                    "日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*销售合同入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "','edit',$('form[name=listForm]').serialize())\">提交检验</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*销售合同列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'orderNo' => $this->post('orderNo'),
//            'model' => $this->post('model'),
            'khid' => $this->post('khid'),
            'coid'=>self::$coid,
//            'type_cylinder'=>2,
//            'state'=>'待质检'
        ];
        $like = [
            'model' => $this->post('model'),
            'code' => $this->post('code'),
            'barcode' => $this->post('barcode'),
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "jsonData->'$.DT_MADE'");
        }
        $page = $this->page(["table" => self::table, "where" => $where.$and, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
            ];
            $liButton[] = $this->dominate($dominate) . hidden(["name" => "cylinderId", "value" => $array['id']]);
            $jsonData = json_decode($array['jsonData'],true);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "wenTime":
                        $row[] = $jsonData['DT_CHECK'] ?? '';
                        break;
                    case "nextTime":
                        $row[] = $jsonData['DT_NEXTCHECK'] ?? '';
                        break;
                    case "dtTime":
                        $row[] = $jsonData['DT_MADE'] ?? '';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] .clear;
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            case 'edit':
                $act      = 'edit';
                $msg      = '修改';
                $title    = '是否检验所选信息？';
                $function = 'edit';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
            default:
                $act      = 'del';
                $msg      = '报废';
                $title    = '是否报废所选信息，报废后不可找回？';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 检验
     * @return bool|string
     */
    public function edit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = '你还没有编辑的权限';
        } elseif (empty($array)) {
            $json['warn'] = '请选择钢瓶信息';
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                //最后删除基本参数
                $info = query(self::table,"id = '" . $id . "'");
                update(["table" => self::table , "field" => [
                    'state' => '质检中',
                ], "where" => "id = '" . $id . "'"]);
                static::insert([
                    "table" =>  self::table.'_log',
                    "field" => [
                        'id'                 => self::getId(),
                        'steelCylinderId'    => $id,
                        'coid'               => self::$coid,
                        'barcode'            => $info['barcode'],
                        'code'               => $info['code'],
                        'model'              => $info['model'],
                        'text'               => '',
                        'state'              => '待检验',
                        'stid'               => self::$stid,
                        'updateTime'         => $this->time,
                        'time'               => $this->time,
                    ],

                ]);
                //返回
                $warn = '质检成功';
                $x++;
                $text .= '钢瓶信息' . $warn . "。<br>";
            }
            //添加日志
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x],"成功质检{{x}}个钢瓶信息，详情请查看日志");
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $jsonData = json_decode($array['jsonData'],true);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '内部编码'=>$array['barcode'],
                            '出厂码'=>$array['code'],
                            '规格型号'=>$array['model'],
                            '下次检验日期'=>$jsonData['DT_NEXTCHECK'] ?? '',
                            '最近检验日期'=>$jsonData['DT_CHECK'] ?? '',
                            '制造日期'=>$jsonData['DT_CHECK'] ?? '',
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了待检验钢瓶表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "待检验钢瓶表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'内部编码',
                    'aliasName'=>'内部编码',
                ],
                [
                    'columnName'=>'出厂码',
                    'aliasName'=>'出厂码',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'下次检验日期',
                    'aliasName'=>'下次检验日期',
                ],
                [
                    'columnName'=>'最近检验日期',
                    'aliasName'=>'最近检验日期',
                ],
                [
                    'columnName'=>'制造日期',
                    'aliasName'=>'制造日期',
                ],
            ]
        };
    }
}